import { GetanTableProps } from "../types"

export interface PageInfo {
    pageNum: number
    pageSize: number
    totalRow: number
}

/**
 * 支持分页
 */
export function usePagination(props: Ref<Partial<GetanTableProps>>) {
    /**
     * 分页数据
     */
    const paginationRef = ref<PageInfo>({
        pageNum: 1,
        pageSize: 20,
        totalRow: 0
    })

    /**
     * 默认使用分页基础用法
     */
    const defaultPagination = {
        // 支持选择每页数量
        showSizePicker: true,
        pageSizes: [20, 50, 100, 200],
        // 显示总条数
        prefix: ({ itemCount }: Recordable) => {
            return `共 ${itemCount} 行`
        }
    }

    const mergedPagination = computed(() => {
        const { usePagination } = unref(props)
        if (!usePagination) {
            return false
        }
        if (usePagination === true) {
            return {
                ...defaultPagination,
                page: paginationRef.value.pageNum,
                pageSize: paginationRef.value.pageSize,
                itemCount: paginationRef.value.totalRow
            }
        } else {
            return Object.assign({}, defaultPagination, usePagination, {
                page: paginationRef.value.pageNum,
                pageSize: paginationRef.value.pageSize,
                itemCount: paginationRef.value.totalRow
            })
        }
    })

    /**
     * 调整页码
     */
    const changePageNum = (pageNum: number) => {
        paginationRef.value.pageNum = pageNum
    }

    /**
     * 调整每页记录数
     */
    const changePageSize = (pageNum: number, pageSize: number) => {
        paginationRef.value.pageNum = pageNum
        paginationRef.value.pageSize = pageSize
    }

    /**
     * 调整每页记录数
     */
    const setPagination = (pageInfo: PageInfo) => {
        paginationRef.value.pageNum = pageInfo.pageNum
        paginationRef.value.pageSize = pageInfo.pageSize
        paginationRef.value.totalRow = pageInfo.totalRow
    }

    /**
     * 获取分页参数
     */
    const getPageParams = (params: Recordable) => {
        params.page = paginationRef.value.pageNum
        params.pageSize = paginationRef.value.pageSize
    }

    return { pagination: mergedPagination, changePageNum, changePageSize, setPagination, getPageParams }
}
